package megrez.mail.sender.domain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import megrez.mail.sender.common.Snowflake;

/**
 * 模板配置
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Getter
@Setter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "mail_template_config")
public class TemplateConfig{
    @Id
    @EqualsAndHashCode.Include
    @Column(updatable = false, nullable = false, unique = true)
    private String id;

    @Version
    @Column(nullable = false)
    private Integer version;

    @CreatedBy
    @Column(updatable = false)
    private String createdBy;

    @CreatedDate
    @Column(updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdDate;

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastModifiedDate;

    /** 内容类型 */
    private MailContentType type;
    /** 代码 */
    private String code;
    /** 备注 */
    private String remark;
    /** 启用 */
    private Boolean enabled;

    /** 内容 */
    @ToString.Exclude
    @OneToMany(mappedBy = "templateConfig", cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
    private List<TemplateContent> contents = new ArrayList<>();

    public TemplateConfig() {
    }

    public TemplateConfig(MailContentType type, String code, String remark, Boolean enabled) {
        this.code = code;
        this.remark = remark;
        this.type = type;
        this.enabled = enabled;
    }

    @PrePersist
    @PreUpdate
    public void preAction() {
        if (getId() == null) {
            setId(Snowflake.nextIdStr());
        }

        if (type == null) {
            type = MailContentType.TEXT;
        }
    }
}
